<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item to="/home/welcome">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryinfo.query"
            @change="getUser"
            clearable
          >
            <el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="dialogFormVisible=true" style="margin-top:8px">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="UserList" border style="width: 100%">
        <el-table-column type="index" label="#" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="权限">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row.id,scope.row.mg_state)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑用户" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" circle @click="editDialog(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" circle @click="open(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" circle @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页效果展示 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户的对话框 -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisible" width="50%" @close="resetForm">
        <el-form
          :model="userinfo"
          label-width="100px"
          :rules="addFormRules"
          :hide-required-asterisk="true"
          ref="userinfo"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userinfo.username" autofocus></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userinfo.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userinfo.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="userinfo.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑用户的对话框 -->
      <el-dialog title="用户信息" :visible.sync="editflag">
        <el-form
          :model="edituser"
          label-width="100px"
          :hide-required-asterisk="false"
          :rules="addFormRules"
          ref="edituser"
        >
          <el-form-item label="用户名">
            <el-input v-model="edituser.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="edituser.mobile"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="edituser.email"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editflag = false">取 消</el-button>
          <el-button type="primary" @click="updateUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色的对话框 -->
      <el-dialog title="分配角色" :visible.sync="roleFlag" width="50%">
        <div>
          <p>当前用户名为：{{userRole.username}}</p>
          <br />
          <p>当前用户角色为：{{userRole.role_name}}</p>
          <br />
          <p>
            分配新角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="roleFlag = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // email验证
    var checkEmail = (rule, value, cb) => {
      const regmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regmail.test(value)) return cb();
      cb(new Error("请输入合法邮箱"));
    };
    var checkmobile = (rule, value, cb) => {
      const regmobile = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
      if (regmobile.test(value)) return cb();
      cb(new Error("请输入合法手机号"));
    };
    return {
      // 查询用户信息的规则
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      // 添加用户的信息
      userinfo: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 查询的user数据
      UserList: [],
      // 总记录条数
      total: 0,
      // 添加的对话框是否能显示
      dialogFormVisible: false,
      // 编辑对话框是否显示
      editflag: false,
      // 分配角色对话框的flag
      roleFlag: false,
      // 被分配权限的角色
      userRole: "",
      // 获取的角色列表数据
      roleList: "",
      // 选中的角色id
      selectRoleId: "",
      edituser: {
        username: "",
        mobile: "",
        email: "",
        id: ""
      },
      // 用户添加的验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户电话", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" }
        ]
      }
    };
  },
  mounted () {
    this.getUser();
  },
  methods: {
    // 获取用户数据
    async getUser () {
      const { data } = await this.axios.get("/users", {
        params: this.queryinfo
      });
      this.UserList = data.users;
      this.total = data.total;
      console.log(data);
    },
    // 添加用户
    addUser () {
      // 在注册发送请求之前最后进行一次校验
      this.$refs.userinfo.validate(valid => {
        if (!valid) return;
        this.axios.post("users", this.userinfo).then(res => {
          // 添加用户成功则显示
          if (res.meta.status == 201) {
            this.$message.success({
              message: res.meta.msg,
              duration: 1000
            });
            //同时取消对话框
            this.dialogFormVisible = false;
            // 重新获取数据
            this.getUser();
          } else
            this.$message.error({
              message: "用户创建失败",
              duration: 1000
            });
        });
      });
    },
    // 编辑更新用户
    updateUser () {
      this.$refs.edituser.validate(valid => {
        if (!valid)
          return this.$message.error({
            message: "请根据规则修改数据",
            duration: 1000
          });
        this.axios.put("users/" + this.edituser.id, this.edituser).then(res => {
          if (res.meta.status == 200) {
            this.$message.success({
              message: "更新用户数据成功",
              duration: 1000
            });
            // 消失对话框
            this.editflag = false;
            // 重新获取数据
            this.getUser();
          } else {
            this.$message.error({
              message: "更新数据失败",
              duration: 1000
            });
          }
        });
      });
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      this.queryinfo.pagesize = newSize;
      this.getUser();
    },
    // 页码发生变化  则触发事件
    handleCurrentChange (newPage) {
      this.queryinfo.pagenum = newPage;
      this.getUser();
    },
    // 改变用户状态 并更新到数据库中
    // 这个函数当输入框点击清空时也会触发   因为绑定的是change事件
    changeState (id, newState) {
      this.axios.put(`users/${id}/state/${newState}`).then(res => {
        // 看是否改变成功 并提示用户
        this.$message.success({ duration: 1000, message: res.meta.msg });
      });
    },
    // 重置dialog中的表单
    resetForm () {
      this.$refs.userinfo.resetFields();
    },
    // 编辑用户对话框的显示信息
    editDialog ({ username, email, mobile, id }) {
      this.editflag = true;
      this.edituser.username = username;
      this.edituser.email = email;
      this.edituser.mobile = mobile;
      this.edituser.id = id;
    },
    // 提示用户是否删除
    open (id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发送请求去删除数据
          this.axios.delete("users/" + id).then(res => {
            if (res.meta.status == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              // 重新获取数据
              this.getUser();
            } else {
              this.$message.error({
                message: "删除失败",
                duration: 1000
              });
            }
          });
        })
        .catch(() => { });
    },
    // 设置角色
    async setRole (userinfo) {
      this.userRole = userinfo;
      let res = await this.axios.get("roles");
      console.log(res);

      if (res.meta.status != 200)
        return this.$message.error({
          message: "获取角色列表失败",
          duration: 1000
        });
      // 获取角色列表信息
      this.roleList = res.data;
      // 同时打开对话框
      this.roleFlag = true;
    },
    // 分配角色
    saveRole () {
      console.log(this.userRole);

      if (!this.selectRoleId)
        return this.$message.error({
          message: "请选择用户角色进行分配",
          duration: 1000
        });
      this.axios
        .put("users/" + this.userRole.id + "/role", { rid: this.selectRoleId })
        .then(res => {
          if (res.meta.status != 200)
            return this.$message.error({
              message: "更新角色失败",
              duration: 1000
            });
          this.$message.success({
            message: "更新角色成功",
            duration: 1000
          });
          this.roleFlag = false;
          //更新角色
          this.getUser();
        });
    }
  }
};
</script>

<style >
.el-card {
  box-shadow: 0 1px 1px rgba(51, 24, 206, 0.15) !important;
  line-height: 0;
  padding-right: 0px !important;
}
.el-input {
  margin-top: 8px;
}
.el-table {
  margin-top: 10px;
}
/* 解决elementui dialog  导致窗口晃动问题 */
.el-popup-parent--hidden {
  padding-right: 0px !important;
  overflow-y: auto !important;
}
.el-form-item__content {
  height: 45px;
}
</style>
